<script setup>
import { getUserOrderAPI } from '@/apis/order'
import { onMounted, ref } from 'vue'
import { imageBaseURL } from '@/utils/request'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

const router = useRouter()
// tab列表
const tabTypes = [
  { name: 'all', label: '全部订单', state: '' },
  { name: 'unpay', label: '待付款', state: 'Processing' },
  { name: 'deliver', label: '待发货', state: 'Paid' },
  { name: 'receive', label: '待收货', state: 'In_Transit' },
  // { name: 'comment', label: '待评价', state: 'Completed' },
  { name: 'complete', label: '已完成', state: 'Completed' },
  { name: 'cancel', label: '已取消', state: 'Closed' }
]
// 创建格式化函数
const fomartPayState = (payState) => {
  const stateMap = {
    'Processing': '待付款',
    'Paid': '已付款',
    'Confirmed': '已确认',
    'Shipped': '已发货',
    'In_Transit': '运输中',
    'Delivered': '已送达',
    'Completed': '已完成',
    'Return': '退货/退款中',
    'Closed': '已关闭'
  }
  return stateMap[payState] || '未知状态'
}
// 订单列表
const orderList = ref([])
const total = ref(0)
const params = ref({
  orderState: '',  // 确保初始值为空字符串
  page: 1,
  pageSize: 2
})

const getUserOrder = async () => {
  try {
    // 创建新的请求参数对象，如果orderState为空则不包含此参数
    const requestParams = { ...params.value }
    if (requestParams.orderState === '') {
      delete requestParams.orderState
    }
    const res = await getUserOrderAPI(requestParams)
    if (res.result && res.result.items) {
      // 对订单列表按照创建时间进行降序排序
      orderList.value = res.result.items.sort((a, b) => {
        return new Date(b.createTime) - new Date(a.createTime)
      })
      total.value = res.result.counts
    } else {
      orderList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    orderList.value = []
    total.value = 0
  }
}

// 确保在组件挂载时初始化数据
onMounted(() => {
  params.value.orderState = ''
  getUserOrder()
})
// 导航栏切换
const tabChange = (index) => {
  const selectedTab = tabTypes[index]
  params.value.orderState = selectedTab.state || ''  // 修改这里，使用空字符串作为默认值
  params.value.page = 1
  getUserOrder()
}
// 页面切换
const pageChange = (page) => {
  params.value.page = page
  getUserOrder()
}

// 查看订单详情
const viewOrderDetail = (orderId) => {
  router.push(`/member/order/${orderId}`)
}

// 立即付款
const handlePay = (orderId) => {
  router.push(`/pay?id=${orderId}`)
}

// 取消订单
const cancelOrder = async (orderId) => {
  try {
    const res = await request({
      url: `/member/order/${orderId}/cancel`,
      method: 'PUT',
      data: {
        orderId: orderId,
        cancelReason: '用户主动取消'
      }
    })
    if (res.msg === '订单取消成功') {
      // 刷新订单列表
      getUserOrder()
      ElMessage.success('订单取消成功')
    } else {
      ElMessage.error(res.msg || '取消订单失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '取消订单失败')
  }
}
// 确认订单状态
const confirmOrderStatus = async (orderId) => {
  console.log('confirmOrderStatus')
  try {
    const res = await request({
      url: `/member/order/${orderId}`,
      method: 'POST',
      data: {
        orderState: 'Completed'
      }
    })
    if (res.code === 200 ) {
      // 刷新订单列表
      getUserOrder()
      ElMessage.success('确认收货成功')
    } else {
      ElMessage.error(res.msg || '确认收货失败')
    }
  } catch (error) {
    ElMessage.error(error.response?.data?.msg || '确认收货失败')
  }
}

</script>

<template>
  <div class="order-container">
    <el-tabs @tab-change="tabChange">
      <!-- tab切换 -->
      <el-tab-pane
        v-for="item in tabTypes"
        :key="item.name"
        :label="item.label"
      />
      <div class="main-container">
        <div class="holder-container" v-if="orderList.length === 0">
          <el-empty description="暂无订单数据" />
        </div>
        <div v-else>
          <!-- 订单列表 -->
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="head">
              <span>下单时间：{{ order.createTime }}</span>
              <span>订单编号：{{ order.id }}</span>
              <!-- 未付款，倒计时时间还有 -->
              <span class="down-time" v-if="order.orderState === 'Processing'">
                <i class="iconfont icon-down-time"></i>
                <b>付款截止: {{ order.countdown }}</b>
              </span>
            </div>
            <div class="body">
              <div class="column goods">
                <ul>
                  <li v-for="item in order.skus" :key="item.id">
                    <a class="image" href="javascript:;">
                      <img :src="imageBaseURL + '/' + item.image" alt="" />
                    </a>
                    <div class="info">
                      <p class="name ellipsis-2">
                        {{ item.name }}
                      </p>
                      <p class="attr ellipsis">
                        <span>{{ item.attrsText }}</span>
                      </p>
                    </div>
                    <div class="price">¥{{ item.realPay?.toFixed(2) }}</div>
                    <div class="count">x{{ item.quantity }}</div>
                  </li>
                </ul>
              </div>
              <div class="column state">
                <p>{{ fomartPayState(order.orderState) }}</p>
                <p v-if="order.orderState === 'Shipped' || order.orderState === 'In_Transit'">
                  <a href="javascript:;" class="green">查看物流</a>
                </p>
                <p v-if="order.orderState === 'Delivered'">
                  <a href="javascript:;" class="green">评价商品</a>
                </p>
                <p v-if="order.orderState === 'Completed'">
                  <!-- <a href="javascript:;" class="green">查看评价</a> -->
                </p>
              </div>
              <div class="column amount">
                <p class="red">¥{{ order.payMoney?.toFixed(2) }}</p>
                <p>（含运费：¥{{ order.postFee?.toFixed(2) }}）</p>
                <p>在线支付</p>
              </div>
              <div class="column action">
                <el-button
                  v-if="order.orderState === 'Processing'"
                  type="primary"
                  size="small"
                  @click="handlePay(order.id)"
                >
                  立即付款
                </el-button>
                <el-button
                  v-if="order.orderState === 'In_Transit'"
                  type="primary"
                  size="small"
                  @click="confirmOrderStatus(order.id)"
                >
                  确认收货
                </el-button>
                <p><a href="javascript:;" @click="viewOrderDetail(order.id)">查看详情</a></p>
                <p v-if="['Paid', 'Shipped', 'In_Transit', 'Delivered', 'Completed'].includes(order.orderState)">
                  <!-- <a href="javascript:;">再次购买</a> -->
                </p>
                <p v-if="['Delivered', 'Completed'].includes(order.orderState)">
                  <!-- <a href="javascript:;">申请售后</a> -->
                </p>
                <p v-if="order.orderState === 'Processing'">
                  <a href="javascript:;" @click="cancelOrder(order.id)">取消订单</a>
                </p>
              </div>
            </div>
          </div>
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              :total="total"
              @current-change="pageChange"
              :page-size="params.pageSize"
              background
              layout="prev, pager, next"
            />
          </div>
        </div>
      </div>
    </el-tabs>
  </div>
</template>

<style scoped lang="scss">
.order-container {
  padding: 10px 20px;

  .pagination-container {
    display: flex;
    justify-content: center;
  }

  .main-container {
    min-height: 500px;

    .holder-container {
      min-height: 500px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.order-item {
  margin-bottom: 20px;
  border: 1px solid #f5f5f5;

  .head {
    height: 50px;
    line-height: 50px;
    background: #f5f5f5;
    padding: 0 20px;
    overflow: hidden;

    span {
      margin-right: 20px;

      &.down-time {
        margin-right: 0;
        float: right;

        i {
          vertical-align: middle;
          margin-right: 3px;
        }

        b {
          vertical-align: middle;
          font-weight: normal;
        }
      }
    }

    .del {
      margin-right: 0;
      float: right;
      color: #999;
    }
  }

  .body {
    display: flex;
    align-items: stretch;

    .column {
      border-left: 1px solid #f5f5f5;
      text-align: center;
      padding: 20px;

      > p {
        padding-top: 10px;
      }

      &:first-child {
        border-left: none;
      }

      &.goods {
        flex: 1;
        padding: 0;
        align-self: center;

        ul {
          li {
            border-bottom: 1px solid #f5f5f5;
            padding: 10px;
            display: flex;

            &:last-child {
              border-bottom: none;
            }

            .image {
              width: 70px;
              height: 70px;
              border: 1px solid #f5f5f5;
            }

            .info {
              width: 220px;
              text-align: left;
              padding: 0 10px;

              p {
                margin-bottom: 5px;

                &.name {
                  height: 38px;
                }

                &.attr {
                  color: #999;
                  font-size: 12px;

                  span {
                    margin-right: 5px;
                  }
                }
              }
            }

            .price {
              width: 100px;
            }

            .count {
              width: 80px;
            }
          }
        }
      }

      &.state {
        width: 120px;

        .green {
          color: $xtxColor;
        }
      }

      &.amount {
        width: 200px;

        .red {
          color: $priceColor;
        }
      }

      &.action {
        width: 140px;

        a {
          display: block;

          &:hover {
            color: $xtxColor;
          }
        }
      }
    }
  }
}
</style>
